package com.hp.bon.sgw.stdbss30.bizSlotOutside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.stdbss30.BizSlot;
import com.hp.bon.sgw.stdbss30.utils.HttpClientUtils;
import com.hp.bon.sgw.stdbss30.common.BizConsts;
import com.hp.bon.sgw.stdbss30.common.BizParam;
import com.hp.bon.sgw.stdbss30.common.BizResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CreditQueryYXHB9BizSlot implements BizSlot {
    private static final Logger _log = LoggerFactory.getLogger(CreditQueryYXHB9BizSlot.class);

    @Override
    public BizResult doBiz(XmlMessage xmlMessage, BizParam bizParam) {
        BizResult bizResult = new BizResult();

        try {
            String queryFlag = HttpClientUtils.getXmlValue(xmlMessage, "/Service_Information/Query_Flag");
            String billingCycle = HttpClientUtils.getXmlValue(xmlMessage, "/Service_Information/Billing_Cycle");
            String destinationAttr = HttpClientUtils.getXmlValue(xmlMessage, "/Service_Information/DestinationAttr");
            String destinationId = HttpClientUtils.getXmlValue(xmlMessage, "/Service_Information/Destination_Id");


            JSONObject stdCcrQueryCredit = new JSONObject();
            stdCcrQueryCredit.put("queryFlag", queryFlag);
            stdCcrQueryCredit.put("billingCycle", billingCycle);
            stdCcrQueryCredit.put("destinationAttr", destinationAttr);
            stdCcrQueryCredit.put("destinationId", destinationId);


            //构建请求条件
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("stdCcrQueryCredit", stdCcrQueryCredit);

            StringBuilder msgBodyStr = new StringBuilder();

            //发送请求
            String webserviceUrl = bizParam.getParamString(BizConsts.KEY_ACCOUNT_API_URL);
            msgBodyStr.append(jsonObject.toJSONString());
               _log.info("request body is {}",msgBodyStr.toString());_log.info("request body is {}",msgBodyStr.toString());
String respStr = HttpClientUtils.postHttpStr(msgBodyStr.toString(), webserviceUrl);
_log.info("response is "+respStr.toString());

            if (respStr.equals("")) {
                bizResult.setCode(BizConsts.STATUS_ACOUNT_API_FAIL);
                return bizResult;
            }

            //解析json 拼接报文
            JSONObject json = JSON.parseObject(respStr);
            StringBuffer buffer = new StringBuffer();
            jsonToXmlStr(xmlMessage, json, buffer);


            bizResult.setHttpBody(buffer.toString());
        } catch (Exception e) {
            bizResult.setCode(BizConsts.STATUS_ACOUNT_API_FAIL);
            _log.info(e.toString());
        }
        return bizResult;
    }

    public static void jsonToXmlStr(XmlMessage xmlMessage, JSONObject json, StringBuffer buffer) {
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        buffer.append("<SOAP-ENV:Header/>");
        buffer.append("<SOAP-ENV:Body>");
        buffer.append("<ns3:SgwQueryAck xmlns:ns3=\"http://www.chinatelecom.cn/SGW/SOAP\">");
        buffer.append("<MID>" + xmlMessage.getMID() + "</MID>");
        buffer.append("<REPTAG>" + xmlMessage.getREPTAG() + "</REPTAG>");
        buffer.append("<RTT>" + xmlMessage.getRTT() + "</RTT>");
        buffer.append("<SIG>" + xmlMessage.getSIG() + "</SIG>");
        buffer.append("<RC>" + xmlMessage.getRC() + "</RC>");
        buffer.append("<DS>" + xmlMessage.getDS() + "</DS>");
        buffer.append("<DATA><![CDATA[<Service_Information>");

        buffer.append("<Result>" + (json.get("errorCode") == null ? "" : json.get("errorCode")) + "</Result>");
        buffer.append("<Data_Information>");
        JSONObject jsonEntry = JSON.parseObject(String.valueOf(JSON.parseObject(String.valueOf(json.get("stdCcaQueryCredit"))).get("creditInfo")));
        buffer.append("<Acc_Nbr>" + (jsonEntry.get("accNbr") == null ? "" : jsonEntry.get("accNbr")) + "</Acc_Nbr>");
        buffer.append("<DestinationAttr>" + (jsonEntry.get("destinationAttr") == null ? "" : jsonEntry.get("destinationAttr")) + "</DestinationAttr>");
        buffer.append("<Credit_available>" + (jsonEntry.get("creditAvailable") == null ? "" : jsonEntry.get("creditAvailable")) + "</Credit_available>");
        buffer.append("<UnitType_Id>" + (jsonEntry.get("unitTypeId") == null ? "" : jsonEntry.get("unitTypeId")) + "</UnitType_Id>");

        String entryListStr = String.valueOf(((JSONObject)((JSONObject)json.get("stdCcaQueryCredit")).get("creditInfo")).get("creditItemDetail"));
        JSONArray jsonArray = JSONArray.parseArray(entryListStr);
        if (!entryListStr.equals("null")) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject entry = (JSONObject) jsonArray.get(i);
                buffer.append("<Credit-Item-Detail>");
                buffer.append("<Credit_value_type>" + (entry.get("creditValueType") == null ? "" : entry.get("creditValueType")) + "</Credit_value_type>");
                buffer.append("<Credit-Amount>" + (entry.get("creditAmount") == null ? "" : entry.get("creditAmount")) + "</Credit-Amount>");
                buffer.append("<StartTime>" + (entry.get("startTime") == null ? "" : entry.get("startTime")) + "</StartTime>");
                buffer.append("<EndTime>" + (entry.get("endTime") == null ? "" : entry.get("endTime")) + "</EndTime>");
                buffer.append("<Credit_Grade>" + (entry.get("creditGrade") == null ? "" : entry.get("creditGrade")) + "</Credit_Grade>");
                buffer.append("<Credit_Score>" + (entry.get("creditScore") == null ? "" : entry.get("creditScore")) + "</Credit_Score>");
                buffer.append("</Credit-Item-Detail>");
            }

        }
        buffer.append("</Data_Information>");

        buffer.append("</Service_Information>]]></DATA>");
        buffer.append("</ns3:SgwQueryAck>");
        buffer.append("</SOAP-ENV:Body>");
        buffer.append("</SOAP-ENV:Envelope>");
    }

}
